/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import { localize, localize2 } from 'vs/nls';
import { Codicon } from 'vs/base/common/codicons';
import { registerIcon } from 'vs/platform/theme/common/iconRegistry';
import { Registry } from 'vs/platform/registry/common/platform';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { ViewContainerLocation, IViewsRegistry, Extensions as ViewsExtensions, IViewContainersRegistry, IViewDescriptor } from 'vs/workbench/common/views';
import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer';
import { WechatViewPane } from './wechatViewPane';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { Disposable } from 'vs/base/common/lifecycle';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IViewsService } from 'vs/workbench/services/views/common/viewsService';
import { EditorExtensions } from 'vs/workbench/common/editor';
import { IEditorFactoryRegistry } from 'vs/workbench/common/editor';
import { EditorPaneDescriptor } from 'vs/workbench/browser/editor';
import { IEditorPaneRegistry } from 'vs/workbench/browser/editor';
import { WechatEditor } from './wechatEditor';
import { WechatEditorInput, WechatEditorInputSerializer } from './wechatEditorInput';

// 注册微信图标
const wechatIcon = registerIcon('wechat-view-icon', Codicon.commentDiscussion, localize('wechatViewIcon', "View icon for the WeChat view."));

// 注册视图容器
const WECHAT_VIEW_CONTAINER_ID = 'workbench.view.wechat';
const viewContainer = Registry.as<IViewContainersRegistry>(ViewsExtensions.ViewContainersRegistry).registerViewContainer({
	id: WECHAT_VIEW_CONTAINER_ID,
	title: localize2('wechat', "WeChat"),
	icon: wechatIcon,
	ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [WECHAT_VIEW_CONTAINER_ID, { mergeViewWithContainerWhenSingleView: true }]),
	storageId: WECHAT_VIEW_CONTAINER_ID,
}, ViewContainerLocation.Sidebar);

// 注册视图
const viewDescriptor: IViewDescriptor = {
	id: WechatViewPane.ID,
	name: localize2('wechat.view', "WeChat"),
	ctorDescriptor: new SyncDescriptor(WechatViewPane),
	containerIcon: wechatIcon,
	canToggleVisibility: true,
	canMoveView: true,
	order: 100,
	when: undefined,
	collapsed: false,
	hideByDefault: false,
	focusCommand: {
		id: 'workbench.action.focusWechatView'
	}
};

// 注册视图到视图容器
Registry.as<IViewsRegistry>(ViewsExtensions.ViewsRegistry).registerViews([viewDescriptor], viewContainer);

// 注册编辑器面板
Registry.as<IEditorPaneRegistry>(EditorExtensions.EditorPane).registerEditorPane(
	EditorPaneDescriptor.create(
		WechatEditor as any,
		WechatEditor.ID,
		localize('wechat.editor', "WeChat")
	),
	[new SyncDescriptor(WechatEditorInput)]
);

// 注册编辑器序列化器
Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).registerEditorSerializer(
	WechatEditorInput.ID,
	WechatEditorInputSerializer
);

// 注册工作台贡献，处理编辑器和视图的联动
class WechatContribution extends Disposable {
	static readonly ID = 'workbench.contrib.wechat';

	constructor(
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IEditorService private readonly editorService: IEditorService,
		@IViewsService private readonly viewsService: IViewsService
	) {
		super();

		console.log('[WechatContribution] Registering wechat contribution');

		// 监听视图可见性变化
		this._register(this.viewsService.onDidChangeViewVisibility(e => {
			if (e.id === WechatViewPane.ID) {
				if (e.visible) {
					// 当视图变为可见时，打开编辑器
					console.log('[WechatContribution] WechatViewPane became visible');
					this.openWechatEditor();
				}
			}
		}));

		// 当点击活动栏项目时，同步打开编辑器
		this._register(this.viewsService.onDidChangeViewContainerVisibility(e => {
			if (e.id === WECHAT_VIEW_CONTAINER_ID && e.visible) {
				// 当WeChat视图容器变为可见时，打开编辑器
				console.log('[WechatContribution] WeChat view container became visible');
				this.openWechatEditor();
			}
		}));
	}

	private openWechatEditor(): void {
		// 检查是否有已打开的编辑器
		const activeEditorPane = this.editorService.activeEditorPane;
		if (activeEditorPane?.input instanceof WechatEditorInput) {
			// 如果已经打开了WeChat编辑器，不做任何操作
			console.log('[WechatContribution] WeChat editor already open');
			return;
		}

		// 否则创建新的编辑器输入
		console.log('[WechatContribution] Opening WeChat editor');
		const editorInput = this.instantiationService.createInstance(WechatEditorInput);
		this.editorService.openEditor(editorInput, {
			pinned: true
		}).then(editor => {
			console.log('[WechatContribution] Editor opened:', editor ? 'success' : 'failed');
		});
	}
}

// 注册工作台贡献
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench)
	.registerWorkbenchContribution(WechatContribution, LifecyclePhase.Restored);
